# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Wild Orange
# @Email: jixuanfan_seu@163.com
# @Date:   2020-06-19 22:38:14
# @Last Modified time: 2020-07-03 10:04:45

import requests
import re
import json
import csv
import time

headers={'User-Agent': 'Chrome/76.0.3809.132'}

#正则表达式提取数据
re_get_js=re.compile(r'<script>([\s\S]*?)</script>')
re_resultList=re.compile(r'"resultList":(\[{.+?}\]),"totalNumFound')
has_statement=False

def Get_company_info(name):
	'''
		@func: 通过百度企业信用查询企业基本信息
	'''
	url='https://xin.baidu.com/s?q=%s'%name
	res=requests.get(url,headers=headers)
	if res.status_code==200:
		html=res.text
		retVal=_parse_baidu_company_info(html)
		return retVal
	else:
		print('无法获取%s的企业信息'%name)

def _parse_baidu_company_info(html):
	'''
		@function：解析百度企业信用提供的企业基本信息
		@output: list of dict, [{},{},...]
			pid: 跳转到具体企业页面的参数
			bid: 具体企业页面URL中的参数
			name: 企业名称
			type: 企业类型
			date: 成立日期
			address: 地址
			person: 法人代表
			status: 存续状态
			regCap: 注册资本
			scope: 经营范围
	'''
	js=re_get_js.findall(html)[1]
	data=re_resultList.search(js)
	if not data:
		return
	compant_list=json.loads(data.group(1))
	
	retVal=[]
	for x in compant_list:
		regCap=x['regCap'].replace(',','')
		if regCap[-1]=='万':
			regCap=regCap[:-1]
		regCap=float(regCap)
		address=x['domicile'].replace('<em>','').replace('</em>','')
		
		temp_v={'pid':x['pid'],'bid':x['bid'],'name':x['titleName'],'type':x['entType'],'date':x['validityFrom'],\
				'address':address,'person':x['legalPerson'],'status':x['openStatus'],'regCap':regCap}
		retVal.append(temp_v)
	return retVal

def __basic():
	statement='/26412/31243/24207/21457/34920/20110/67/83/68/78/65292/26410/21457/34920/20110/\
	20854/20182/24179/21488/65281/10/20316/32773/65306/119/105/108/100/95/111/114/97/110/103/\
	101/10/20010/20154/20027/39029/65306/104/116/116/112/115/58/47/47/98/108/111/103/46/99/115/\
	100/110/46/110/101/116/47/113/113/95/51/53/52/48/56/48/51/48/10/22914/26524/35273/24471/25991/\
	31456/26377/24110/21161/65292/27426/36814/28857/20010/36190/126/35874/35874/65281'
	info=statement.split('/')[1:]
	outVal=''
	for x in info:
		outVal+=chr(int(x))
	return outVal

start = time.time()
f = open('企业.csv','r')
reader=csv.reader(f)
for n in list(reader):
    res=Get_company_info(n[0])
    f1=open('企业地址.csv','a',newline='')
    writer=csv.writer(f1)
    if res==None:
        print(n[0]+",企业地址不存在")
        writer.writerow([])
    else:
        print(n[0]+"企业地址为"+res[0]["address"])
        writer.writerow(([res[0]["address"]]))
    f1.close()
    time.sleep(1)
end = time.time()
print(end-start) 